import { CellPosition } from '../types'

// Note: Make sure to import '../styles/context-menu.css' in your main application

export interface ContextMenuItem {
  id?: string
  label?: string
  icon?: string
  shortcut?: string
  divider?: boolean
  disabled?: boolean
  handler?: () => void
  children?: ContextMenuItem[]
  type?: string
  onClick?: () => void
}

export class ContextMenu {
  private menu: HTMLElement | null = null
  private items: ContextMenuItem[] = []
  private isVisible: boolean = false
  
  constructor() {
    this.createMenu()
    this.bindEvents()
  }
  
  // 创建菜单DOM
  private createMenu(): void {
    this.menu = document.createElement('div')
    this.menu.className = 'canvas-table-context-menu'
    
    // 添加内联样式以确保菜单显示
    this.menu.style.cssText = `
      position: fixed;
      background-color: white;
      border: 1px solid #e5e7eb;
      border-radius: 8px;
      box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05);
      padding: 4px 0;
      z-index: 9999;
      display: none;
      visibility: hidden;
      font-size: 14px;
      font-family: ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto;
      min-width: 200px;
      max-width: 300px;
      width: auto;
      box-sizing: border-box;
    `
    
    document.body.appendChild(this.menu)
  }
  
  // 绑定事件
  private bindEvents(): void {
    // 点击其他地方隐藏菜单
    document.addEventListener('click', (e) => {
      if (this.menu && !this.menu.contains(e.target as Node)) {
        this.hide()
      }
    })
    
    // ESC键隐藏菜单
    document.addEventListener('keydown', (e) => {
      if (e.key === 'Escape' && this.isVisible) {
        this.hide()
      }
    })
  }
  
  // 设置菜单项
  setItems(items: ContextMenuItem[]): void {
    this.items = items
    this.renderMenu()
  }
  
  // 渲染菜单
  private renderMenu(): void {
    if (!this.menu) return
    
    this.menu.innerHTML = ''
    
    this.items.forEach((item, index) => {
      if (item.divider) {
        const divider = document.createElement('div')
        divider.className = 'menu-item-divider'
        divider.style.cssText = 'height: 1px; background-color: #e5e7eb; margin: 4px 0;'
        this.menu!.appendChild(divider)
      } else {
        const menuItem = this.createMenuItem(item)
        this.menu!.appendChild(menuItem)
      }
    })
  }
  
  // 创建菜单项
  private createMenuItem(item: ContextMenuItem): HTMLElement {
    const menuItem = document.createElement('div')
    menuItem.className = 'menu-item'
    
    // 添加内联样式
    menuItem.style.cssText = `
      padding: 8px 16px;
      cursor: pointer;
      display: flex;
      align-items: center;
      justify-content: space-between;
      color: #374151;
      position: relative;
      transition: all 0.2s;
      white-space: nowrap;
      min-height: 32px;
    `
    
    if (item.disabled) {
      menuItem.setAttribute('disabled', 'true')
      menuItem.style.color = '#9ca3af'
      menuItem.style.pointerEvents = 'none'
    }
    
    // 鼠标悬停效果
    if (!item.disabled) {
      menuItem.addEventListener('mouseenter', () => {
        menuItem.style.backgroundColor = '#dbeafe'
        menuItem.style.color = '#2563eb'
        
        // 显示子菜单
        if (item.children && item.children.length > 0) {
          this.showSubmenu(menuItem, item.children)
        }
      })
      
      menuItem.addEventListener('mouseleave', () => {
        menuItem.style.backgroundColor = 'transparent'
        menuItem.style.color = '#374151'
        
        // 延迟移除子菜单，避免鼠标移动到子菜单时消失
        setTimeout(() => {
          const submenu = menuItem.querySelector('.submenu')
          if (submenu && !menuItem.matches(':hover')) {
            submenu.remove()
          }
        }, 100)
      })
      
      // 如果没有子菜单，点击执行处理器
      if (!item.children || item.children.length === 0) {
        menuItem.addEventListener('click', () => {
          if (item.handler) {
            item.handler()
          }
          this.hide()
        })
      }
    }
    
    // 标签部分
    const labelPart = document.createElement('div')
    labelPart.className = 'menu-item-label'
    labelPart.style.cssText = 'display: flex; align-items: center; gap: 8px;'
    
    // 图标
    if (item.icon) {
      const icon = document.createElement('span')
      icon.className = 'menu-item-icon'
      icon.style.cssText = 'width: 16px; height: 16px; display: flex; align-items: center; justify-content: center;'
      icon.innerHTML = item.icon
      labelPart.appendChild(icon)
    }
    
    // 标签文本
    const label = document.createElement('span')
    label.textContent = item.label || ''
    labelPart.appendChild(label)
    
    menuItem.appendChild(labelPart)
    
    // 快捷键
    if (item.shortcut) {
      const shortcut = document.createElement('span')
      shortcut.className = 'menu-item-shortcut'
      shortcut.style.cssText = 'color: #9ca3af; font-size: 12px; margin-left: 24px;'
      shortcut.textContent = item.shortcut
      menuItem.appendChild(shortcut)
    }
    
    // 子菜单箭头
    if (item.children && item.children.length > 0) {
      const arrow = document.createElement('span')
      arrow.className = 'menu-item-arrow'
      arrow.style.cssText = 'color: #9ca3af; font-size: 10px; margin-left: 16px;'
      arrow.innerHTML = '▶'
      menuItem.appendChild(arrow)
    }
    
    return menuItem
  }
  
  // 显示子菜单
  private showSubmenu(parentItem: HTMLElement, items: ContextMenuItem[]): void {
    // 移除已存在的子菜单
    const existingSubmenu = parentItem.querySelector('.submenu')
    if (existingSubmenu) {
      existingSubmenu.remove()
    }
    
    // 创建子菜单
    const submenu = document.createElement('div')
    submenu.className = 'submenu'
    
    // 渲染子菜单项
    items.forEach(item => {
      if (item.divider) {
        const divider = document.createElement('div')
        divider.className = 'menu-item-divider'
        submenu.appendChild(divider)
      } else {
        const subMenuItem = this.createMenuItem(item)
        submenu.appendChild(subMenuItem)
      }
    })
    
    parentItem.appendChild(submenu)
    
    // 确保子菜单不会超出视口
    setTimeout(() => {
      const rect = submenu.getBoundingClientRect()
      if (rect.right > window.innerWidth) {
        submenu.style.left = 'auto'
        submenu.style.right = '100%'
      }
      if (rect.bottom > window.innerHeight) {
        submenu.style.top = 'auto'
        submenu.style.bottom = '0'
      }
    }, 0)
  }
  
  // 显示菜单
  show(x: number, y: number): void {
    if (!this.menu) {
      return
    }
    
    // 先设置为 block 但在屏幕外，以便测量尺寸
    this.menu.style.display = 'block'
    this.menu.style.visibility = 'hidden'
    this.menu.style.left = '-9999px'
    this.menu.style.top = '-9999px'
    
    // 强制重新计算样式
    this.menu.offsetHeight // 触发重排
    
    // 获取菜单的实际尺寸
    const rect = this.menu.getBoundingClientRect()
    
    const viewportWidth = window.innerWidth
    const viewportHeight = window.innerHeight
    
    // 调整水平位置
    let finalX = x
    if (x + rect.width > viewportWidth) {
      finalX = viewportWidth - rect.width - 10
    }
    
    // 调整垂直位置
    let finalY = y
    if (y + rect.height > viewportHeight) {
      finalY = viewportHeight - rect.height - 10
    }
    
    // 确保不会超出左边和上边界
    finalX = Math.max(10, finalX)
    finalY = Math.max(10, finalY)
    
    // 设置最终位置并显示
    this.menu.style.left = `${finalX}px`
    this.menu.style.top = `${finalY}px`
    this.menu.style.visibility = 'visible'
    this.isVisible = true
  }
  
  // 隐藏菜单
  hide(): void {
    if (!this.menu) return
    
    this.menu.style.display = 'none'
    this.menu.style.visibility = 'hidden'
    this.isVisible = false
  }
  
  // 销毁菜单
  destroy(): void {
    if (this.menu) {
      this.menu.remove()
      this.menu = null
    }
  }
  
  // 创建默认的表格上下文菜单
  static createTableContextMenu(params: {
    selectedCells: CellPosition[]
    selectedRows?: number[]
    selectedColumns?: number[]
    hasChanges: boolean
    canUndo: boolean
    canRedo: boolean
    onCopy: () => void
    onPaste: () => void
    onCut: () => void
    onDelete: () => void
    onInsertRow: () => void
    onDeleteRow: () => void
    onSelectRow?: () => void
    onSelectColumn?: () => void
    onSelectAll?: () => void
    onBatchEdit?: () => void
    onBatchFill?: (direction: string) => void
    onBatchClear?: () => void
    onUndo: () => void
    onRedo: () => void
  }): ContextMenuItem[] {
    const hasSelection = params.selectedCells.length > 0 || 
                        (params.selectedRows && params.selectedRows.length > 0) ||
                        (params.selectedColumns && params.selectedColumns.length > 0)
    
    const hasRowSelection = params.selectedRows && params.selectedRows.length > 0
    const rowCount = hasRowSelection ? params.selectedRows!.length : 
                     (params.selectedCells.length > 0 ? new Set(params.selectedCells.map(c => c.row)).size : 0)
    
    return [
      {
        id: 'undo',
        label: '撤销',
        icon: '↶',
        shortcut: 'Ctrl+Z',
        disabled: !params.canUndo,
        handler: params.onUndo
      },
      {
        id: 'redo',
        label: '重做',
        icon: '↷',
        shortcut: 'Ctrl+Y',
        disabled: !params.canRedo,
        handler: params.onRedo
      },
      { divider: true },
      {
        id: 'cut',
        label: '剪切',
        icon: '✂',
        shortcut: 'Ctrl+X',
        disabled: !hasSelection,
        handler: params.onCut
      },
      {
        id: 'copy',
        label: '复制',
        icon: '📋',
        shortcut: 'Ctrl+C',
        disabled: !hasSelection,
        handler: params.onCopy
      },
      {
        id: 'paste',
        label: '粘贴',
        icon: '📄',
        shortcut: 'Ctrl+V',
        handler: params.onPaste
      },
      {
        id: 'delete',
        label: '删除',
        icon: '🗑',
        shortcut: 'Delete',
        disabled: !hasSelection,
        handler: params.onDelete
      },
      { divider: true },
      {
        id: 'batch-edit',
        label: '批量编辑',
        icon: '✏',
        disabled: !hasSelection || !params.onBatchEdit,
        handler: params.onBatchEdit
      },
      {
        id: 'batch-clear',
        label: '批量清空',
        icon: '🧹',
        disabled: !hasSelection || !params.onBatchClear,
        handler: params.onBatchClear
      },
      {
        id: 'batch-fill',
        label: '批量填充',
        icon: '📐',
        disabled: !hasSelection || !params.onBatchFill,
        children: [
          {
            id: 'fill-down',
            label: '向下填充',
            icon: '↓',
            handler: () => params.onBatchFill?.('down')
          },
          {
            id: 'fill-up',
            label: '向上填充',
            icon: '↑',
            handler: () => params.onBatchFill?.('up')
          },
          {
            id: 'fill-right',
            label: '向右填充',
            icon: '→',
            handler: () => params.onBatchFill?.('right')
          },
          {
            id: 'fill-left',
            label: '向左填充',
            icon: '←',
            handler: () => params.onBatchFill?.('left')
          }
        ]
      },
      { divider: true },
      {
        id: 'select-row',
        label: '选择整行',
        icon: '↔',
        handler: params.onSelectRow,
        disabled: !params.onSelectRow
      },
      {
        id: 'select-column',
        label: '选择整列',
        icon: '↕',
        handler: params.onSelectColumn,
        disabled: !params.onSelectColumn
      },
      {
        id: 'select-all',
        label: '全选',
        icon: '⊞',
        shortcut: 'Ctrl+A',
        handler: params.onSelectAll,
        disabled: !params.onSelectAll
      },
      { divider: true },
      {
        id: 'insert-row',
        label: '插入行',
        icon: '➕',
        handler: params.onInsertRow
      },
      {
        id: 'delete-row',
        label: hasRowSelection ? `删除选中的 ${rowCount} 行` : '删除行',
        icon: '➖',
        disabled: !hasSelection,
        handler: params.onDeleteRow
      }
    ]
  }
  
  // 创建列头右键菜单
  static createColumnHeaderContextMenu(params: {
    column: any
    columnIndex: number
    currentSortColumn?: string | null
    currentSortDirection?: 'asc' | 'desc' | null
    onSortAsc: () => void
    onSortDesc: () => void
    onClearSort: () => void
    onInsertColumnBefore?: () => void
    onInsertColumnAfter?: () => void
    onDeleteColumn?: () => void
    onColumnProperties?: () => void
  }): ContextMenuItem[] {
    const items: ContextMenuItem[] = []
    
    // 排序选项（如果列支持排序）
    if (params.column.sortable !== false) {
      const isSorted = params.currentSortColumn === params.column.field
      const isAsc = isSorted && params.currentSortDirection === 'asc'
      const isDesc = isSorted && params.currentSortDirection === 'desc'
      
      items.push({
        id: 'sort-asc',
        label: '升序排序',
        icon: '↑',
        disabled: isAsc,
        handler: params.onSortAsc
      })
      
      items.push({
        id: 'sort-desc',
        label: '降序排序',
        icon: '↓',
        disabled: isDesc,
        handler: params.onSortDesc
      })
      
      if (isSorted) {
        items.push({
          id: 'clear-sort',
          label: '取消排序',
          icon: '✕',
          handler: params.onClearSort
        })
      }
      
      items.push({ divider: true })
    }
    
    // 列操作
    if (params.onInsertColumnBefore) {
      items.push({
        id: 'insert-column-before',
        label: '在左侧插入列',
        icon: '←',
        handler: params.onInsertColumnBefore
      })
    }
    
    if (params.onInsertColumnAfter) {
      items.push({
        id: 'insert-column-after',
        label: '在右侧插入列',
        icon: '→',
        handler: params.onInsertColumnAfter
      })
    }
    
    if (params.onDeleteColumn) {
      items.push({
        id: 'delete-column',
        label: '删除列',
        icon: '🗑',
        handler: params.onDeleteColumn
      })
    }
    
    if (params.onColumnProperties) {
      if (items.length > 0 && items[items.length - 1].divider !== true) {
        items.push({ divider: true })
      }
      
      items.push({
        id: 'column-properties',
        label: '列属性',
        icon: '⚙',
        handler: params.onColumnProperties
      })
    }
    
    return items
  }
}